package com.graduation.mybatis.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.graduation.mybatis.bean.User;
import com.graduation.mybatis.service.UserService;
import com.graduation.mybatis.util.AesCbcUtil;
import com.graduation.mybatis.util.HttpRequest;

import jakarta.annotation.Resource;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * (User)表控制层
 *
 * @author makejava
 * @since 2025-03-30 17:26:22
 */
@RestController
@RequestMapping("user")
public class UserController {

    String appID = "wxb9164c972ad2a149";
    String appSecret = "803a8e9ba5adb69fcf742e1f7bf66e55";

    /**
     * 服务对象
     */
    @Autowired
    private UserService userService;

    /**
     * 分页查询
     */
//    @GetMapping("/page")
//    public ResponseEntity<Page<User>> queryByPage(User user, PageRequest pageRequest) {
//        Page<User> page = new Page<>(pageRequest.getPageNum(), pageRequest.getPageSize());
//        QueryWrapper<User> wrapper = new QueryWrapper<>(user);
//        return ResponseEntity.ok(userService.page(page, wrapper));
//    }


    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    public ResponseEntity<User> queryById(@PathVariable Integer id) {
        return ResponseEntity.ok(this.userService.getById(id));
    }

    /**
     * 新增数据
     *
     * @param user 实体
     * @return 新增结果
     */
    @PostMapping
    public ResponseEntity<User> add(User user) {
        return userService.save(user) ?
                ResponseEntity.ok(user) :
                ResponseEntity.internalServerError().build();
    }

    /**
     * 编辑数据
     *
     * @param user 实体
     * @return 编辑结果
     */
    @PutMapping
    public ResponseEntity<User> edit(User user) {
        return userService.updateById(user) ?
                ResponseEntity.ok(user) :
                ResponseEntity.internalServerError().build();
    }

    /**
     * 删除数据
     *
     * @param id 主键
     * @return 删除是否成功
     */
    @DeleteMapping
    public ResponseEntity<Boolean> deleteById(@PathVariable Integer id) {
        return ResponseEntity.ok(this.userService.removeById(id));
    }


    @RequestMapping("/getOpenid")
    @ResponseBody
    public Map getOpenid(String encryptedData, String iv, String code) {
        Map map = new HashMap();
        //登录凭证不能为空
        if (code == null || code.length() == 0) {
            map.put("code", 0);
            map.put("msg", "code 不能为空");
            return map;
        }

        //小程序唯一标识   (在微信小程序管理后台获取)
        String wxspAppid = appID;
        //小程序的 app secret (在微信小程序管理后台获取)
        String wxspSecret = appSecret;
        //授权（必填）
        String grant_type = "authorization_code";
        String grant_type2 = "client_credential";


        // 1、向微信服务器 使用登录凭证 code 获取 session_key 和 openid
        //请求参数
        String params = "appid=" + wxspAppid + "&secret=" + wxspSecret + "&js_code=" + code + "&grant_type=" + grant_type;
        String params2 = "appid=" + wxspAppid + "&secret=" + wxspSecret + "&grant_type=" + grant_type2;
        //发送请求
        String sr = HttpRequest.sendGet("https://api.weixin.qq.com/sns/jscode2session", params);
        String sr2 = HttpRequest.sendGet("https://api.weixin.qq.com/cgi-bin/token", params2);
        //解析相应内容（转换成json对象）
        JSONObject json = JSONObject.fromObject(sr);
        JSONObject json2 = JSONObject.fromObject(sr2);
        //获取会话密钥（session_key）
        String session_key = json.get("session_key").toString();
        String access_token = json2.get("access_token").toString();
        //用户的唯一标识（openid）
        String openid = (String) json.get("openid");

        // 2、对encryptedData加密数据进行AES解密
        try {
            String result = AesCbcUtil.decrypt(encryptedData, session_key, iv, "UTF-8");
            if (null != result && result.length() > 0) {
                map.put("code", 1);
                map.put("msg", "解密成功");


                JSONObject userInfoJSON = JSONObject.fromObject(result);
                User user = new User();
                user.setNickname((String)userInfoJSON.get("nickName"));
                user.setAvatarUrl((String)userInfoJSON.get("avatarUrl"));
                user.setOpenId((String) userInfoJSON.get("openId"));
                user.setGender((int)userInfoJSON.get("gender"));
//                User user1=userService.selectUserByOpenId(user.getOpenId());
//                if(user1!=null) {
//                    userService.updateUserInfo(user);
//                    user.setId(user1.getId());
//                }else {
//                    userService.addWXUserInfo(user);
//                }

                Map userInfo = new HashMap();
                userInfo.put("openId", userInfoJSON.get("openId"));
                userInfo.put("nickName", userInfoJSON.get("nickName"));
                userInfo.put("gender", userInfoJSON.get("gender"));
                userInfo.put("city", userInfoJSON.get("city"));
                userInfo.put("province", userInfoJSON.get("province"));
                userInfo.put("country", userInfoJSON.get("country"));
                userInfo.put("avatarUrl", userInfoJSON.get("avatarUrl"));
                userInfo.put("unionId", userInfoJSON.get("unionId"));
                userInfo.put("accessToken",access_token);
                userInfo.put("id",user.getUserId());
//                if(user1!=null) {
//                    userInfo.put("qq",user1.getQq());
//                    userInfo.put("email",user1.getEmail());
//                    userInfo.put("phone",user1.getPhone());
//                    userInfo.put("schoolId",user1.getSchoolId());
//                    userInfo.put("schoolName",user1.getSchoolName());
//                    userInfo.put("deptId",user1.getDeptId());
//                    userInfo.put("deptName",user1.getDeptName());
//                    userInfo.put("majorId",user1.getMajorId());
//                    userInfo.put("majorName",user1.getMajorName());
//                    userInfo.put("addr",user1.getAddr());
//                    userInfo.put("remark",user1.getRemark());
//                    userInfo.put("userName",user1.getUserName());
//                    userInfo.put("idNum,",user1.getIdNum());
//                    userInfo.put("status,",user1.getStatus());
//                }
                map.put("userInfo", userInfo);
                return map;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        map.put("code", 0);
        map.put("msg", "解密失败");
        return map;
    }

    /**
     * 获得openid / session_key
     * @param request
     * @return
     */
    @PostMapping("/wechatlogin")
    @ResponseBody
    public Map<String, Object> wechatLogin(@RequestBody Map<String, Object> request) {
        Map<String, Object> result = new HashMap<>();
        // 获取 code 参数并进行类型检查
        Object codeObj = request.get("code");
        if (codeObj == null) {
            result.put("code", 0);
            result.put("msg", "code 不能为空");
            return result;
        }

        // 确保 code 是字符串类型
        String code;
        if (codeObj instanceof String) {
            code = (String) codeObj;
        } else if (codeObj instanceof LinkedHashMap) {
            LinkedHashMap<?, ?> linkedHashMap = (LinkedHashMap<?, ?>) codeObj;
            code = String.valueOf(linkedHashMap.get("code"));
        } else {
            result.put("code", 0);
            result.put("msg", "code 必须是字符串或数字类型");
            return result;
        }

        // 校验 code 是否为空
        if (code.isEmpty()) {
            result.put("code", 0);
            result.put("msg", "code 不能为空");
            return result;
        }

        // 调用微信接口获取 openid 和 session_key
        String wxspAppid = appID; // 微信小程序 AppID
        String wxspSecret = appSecret; // 微信小程序 AppSecret
        String grantType = "authorization_code";

        // 构建请求参数
        String params = "appid=" + wxspAppid + "&secret=" + wxspSecret + "&js_code=" + code + "&grant_type=" + grantType;

        // 发送请求
        String response = HttpRequest.sendGet("https://api.weixin.qq.com/sns/jscode2session", params);

        // 解析响应
        JSONObject json = JSONObject.fromObject(response);
        String openid = json.getString("openid");
        String sessionKey = json.getString("session_key");

        // 校验 openid 和 sessionKey 是否为空
        if (openid == null || sessionKey == null) {
            result.put("code", 0);
            result.put("msg", "获取 openid 或 session_key 失败");
            return result;
        }

        // 根据 openid 查询用户是否已注册
        User user = userService.selectUserByOpenId(openid);
        if (user == null) {
            // 用户未注册，创建新用户
            user = new User();
            user.setOpenId(openid);
            user.setSessionKey(sessionKey);
            userService.save(user); // 插入新用户
        } else {
            // 用户已注册，更新 sessionKey
            user.setSessionKey(sessionKey);
            userService.updateUserById(user);
        }
        // 返回用户信息
        result.put("code", 200);
        result.put("msg", "登录成功");
        result.put("data", user);
        return result;
    }

    /**
     * 验证手机号
     * @param request
     * @return
     */
    @RequestMapping("/decryptPhoneNumber")
    @ResponseBody
    public Map<String, Object> decryptPhoneNumber(@RequestBody Map<String, String> request) {
        Map<String, Object> result = new HashMap<>();
        String encryptedData = request.get("encryptedData");
        String iv = request.get("iv");
        String sessionKey = request.get("sessionKey");
        String openid = request.get("openId");

        // 校验参数是否为空
        if (encryptedData == null || iv == null || sessionKey == null) {
            result.put("code", 0);
            result.put("msg", "参数不能为空");
            return result;
        }

        // 解密手机号
        try {
            String decryptedData = AesCbcUtil.decrypt(encryptedData, sessionKey, iv, "UTF-8");
            if (decryptedData != null) {
                JSONObject phoneNumberObj = JSONObject.fromObject(decryptedData);
                String phoneNumber = phoneNumberObj.getString("purePhoneNumber");

                User user = userService.selectUserByOpenId(openid);
                if (user == null) {
                    // 用户未注册，创建新用户
                    user = new User();
                    user.setOpenId(openid);
                    user.setSessionKey(sessionKey);
                    user.setPhoneNumber(phoneNumber);
                    userService.save(user);
                } else {
                    // 用户已注册，更新 sessionKey 和手机号
                    user.setSessionKey(sessionKey);
                    user.setPhoneNumber(phoneNumber);
                    userService.updateUserById(user);
                }

                // 返回用户信息
                result.put("code", 200);
                result.put("msg", "解密成功");
                result.put("data", new HashMap<String, String>() {{
                    put("phoneNumber", phoneNumber);
                }});
                return result;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        result.put("code", 0);
        result.put("msg", "解密失败");
        return result;
    }

}

